﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Client;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TeamFoundation;

namespace UCL.Powersource.TFS
{
    internal class VSEnv : IVSEnv
    {
        private EnvDTE80.DTE2 _dte2;
        private EnvDTE80.DTE2 dte2
        {
            get
            {
                if (_dte2 == null)
                {
                    EnvDTE.IVsExtensibility extensibility = PowersourcePackage.GetGlobalService(typeof(EnvDTE.IVsExtensibility)) as EnvDTE.IVsExtensibility;
                    _dte2 = (EnvDTE80.DTE2)extensibility.GetGlobalsObject(null).DTE;
                }
                return _dte2;
            }
        }

        internal VSEnv(EnvDTE80.DTE2 dte2)
        {
            this._dte2 = dte2;
        }

        public void ExecuteCommand(string command)
        {
            dte2.ExecuteCommand(command);
        }

        private TeamFoundationServerExtAdapter _TeamFoundationServerExt;

        public ITeamFoundationServerExt TeamFoundationServerExt
        {
            get
            {
                if (_TeamFoundationServerExt == null)
                    _TeamFoundationServerExt = new TeamFoundationServerExtAdapter((TeamFoundationServerExt)dte2.GetObject("Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt"));

                return _TeamFoundationServerExt;
            }
        }

        ILog _Log;
        ILog Log
        {
            get { 
                if (_Log == null) _Log = LogManager.GetLog(this.GetType());
                return _Log;
            }

        }

        public void SetTfsContext(ITfsTeamProjectCollection TeamProjectCollection, string TeamUri, bool IsTfsConnected)
        {
            var rifcm = (ITeamFoundationContextManager)Package.GetGlobalService(typeof(ITeamFoundationContextManager));

            if (rifcm != null && IsTfsConnected && TeamProjectCollection !=null && TeamProjectCollection.Uri.ToString() == rifcm.CurrentContext.DomainUri() && TeamUri == rifcm.CurrentContext.ProjectUri()) return;

            if (TeamProjectCollection != null)
            {
                Log.DebugMethod("TeamProjectCollection={0}", TeamProjectCollection);
                var tfscol = ((TfsTeamProjectCollectionAdapter)TeamProjectCollection).TfsTeamProjectCollection;
                Log.DebugMethod("Calling rifcm.SetContext({0}, {1});", tfscol, TeamUri);
                rifcm.SetContext(tfscol, TeamUri);
            }
            else
            {
                Log.DebugMethod("Calling rifcm.SetContext(null, null);");
                rifcm.SetContext(null, null);
            }
        }
    }
}
